package com.hua.utility.encrypt;

import java.io.IOException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class UtilEncryptReversSimple {

	private static final String encryptCode = "(+-*/!@#$%^&H3.)";

	/**
	 * BASE64加密(可逆加密)
	 * 
	 * BASE64 严格地说，属于编码格式，而非加密算法
	 * 
	 * @param key
	 * @return
	 * 
	 */
	private static String encryptBASE64(byte[] key) {
		return (new BASE64Encoder()).encodeBuffer(key);
	}

	/**
	 * BASE64解密
	 * 
	 * @param key
	 * @return
	 * @throws IOException
	 * 
	 */
	private static byte[] decryptBASE64(String key) throws IOException {
		return (new BASE64Decoder()).decodeBuffer(key);
	}

	/**
	 * DES加密
	 * 
	 * @throws Exception
	 * 
	 */
	private static byte[] encryptDES(byte[] datasource, String code) throws Exception {
		SecureRandom random = new SecureRandom();
		DESKeySpec desKey = new DESKeySpec(code.getBytes());
		SecretKey securekey = SecretKeyFactory.getInstance("DES").generateSecret(desKey);
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
		return cipher.doFinal(datasource);
	}

	/**
	 * DES解密
	 * 
	 * @throws Exception
	 */
	private static byte[] decryptDES(byte[] src, String code) throws Exception {
		SecureRandom random = new SecureRandom();
		DESKeySpec desKey = new DESKeySpec(code.getBytes());
		SecretKey securekey = SecretKeyFactory.getInstance("DES").generateSecret(desKey);
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.DECRYPT_MODE, securekey, random);
		return cipher.doFinal(src);
	}

	public static String encrypt(String enString) {
		String resultStr = "";
		try {
			byte[] resultDes = encryptDES(enString.getBytes(), encryptCode);
			String resultBase64 = encryptBASE64(resultDes);
			resultStr = resultBase64;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultStr.replaceAll("\n", "").replaceAll("\r", "");

	}

	public static String decrypt(String deString) {
		String resultStr = "";
		try {
			byte[] resultDes = decryptBASE64(deString);
			byte[] resultBASE64 = decryptDES(resultDes, encryptCode);
			resultStr = new String(resultBASE64);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultStr;
	}

	public static boolean compareEncrypt(String newPwd, String encryptPwd) {
		String oldPwd = decrypt(encryptPwd);
		if (oldPwd != null && oldPwd.equals(newPwd)) {
			return true;
		}
		return false;
	}
}